package ua.javatr.android.smb;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

/**
 * Created by Вячеслав on 10.06.2014.
 */

@SuppressLint("NewApi")
public class DialogFragmentAddCard extends DialogFragment {


    private EditText etCardNumber, etCardName;
    private Spinner spBanks;
    private Button btnNegative, btnPositive;

    private OnDataCompleteListener onDataCompleteListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        onDataCompleteListener = (OnDataCompleteListener) activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dialog_add_card, null);
        getDialog().setTitle("Добавьте новую карту");

        etCardNumber = (EditText) view.findViewById(R.id.etCardNumber);
        etCardName = (EditText) view.findViewById(R.id.etCardName);
        spBanks = (Spinner) view.findViewById(R.id.spBanks);
        btnNegative = (Button) view.findViewById(R.id.btnNegative);
        btnPositive = (Button) view.findViewById(R.id.btnPositive);
        btnNegative.setOnClickListener(btnListener);
        btnPositive.setOnClickListener(btnListener);

        return view;
    }

    View.OnClickListener btnListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btnNegative:
                    getDialog().dismiss();
                    break;
                case R.id.btnPositive:
                    if (etCardNumber.getText().toString().length() != 16) {
                        etCardNumber.setError("Введите номер карты (осталось " + (16 - etCardNumber.getText().toString().length()) + " цифр)");
                        return;
                    }
                    writeToDB();
                    getDialog().dismiss();
                    break;
            }
        }
    };

    private void writeToDB() {
        onDataCompleteListener.onDataComplete(etCardNumber.getText().toString(), etCardName.getText().toString(), (String) spBanks.getSelectedItem());
    }

    public interface OnDataCompleteListener {
        void onDataComplete(String cardNumber, String cardName, String bankName);
    }

}